package com.kaka.bus.engine.borrow.idcard;

import android.Manifest;
import android.content.Intent;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.kaka.bus.AppCenter;
import com.kaka.bus.R;
import com.kaka.bus.base.BaseActivity;
import com.kaka.bus.bean.HttpWrapper;
import com.kaka.bus.bean.IDCardFrontBean;
import com.kaka.bus.constant.Constant;
import com.kaka.bus.constant.UserConstant;
import com.kaka.bus.listener.Listener;
import com.kaka.bus.manager.Result;
import com.kaka.bus.manager.T;
import com.kaka.bus.util.Base64En;
import com.kaka.bus.util.U;
import com.kaka.bus.view.GlideOval;
import com.megvii.idcardquality.IDCardQualityLicenseManager;
import com.megvii.licensemanager.Manager;
import com.tbruyelle.rxpermissions2.RxPermissions;

import butterknife.BindView;
import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.FlowableOnSubscribe;

/**
 * Created by zhangqi on 2016/10/19.
 * e-mail : ${email}
 * desc :
 */

public class IdCardFrontActivity extends BaseActivity<IdCardPresenter> implements IdCardContract.View {


    @BindView(R.id.toolbar_back)
    ImageView mToolbarBack;
    @BindView(R.id.toolbar_name)
    TextView mToolbarName;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.iv_idcard)
    ImageView mIvIdcard;
    @BindView(R.id.tv_idcard)
    TextView mTvIdcard;
    @BindView(R.id.tv_idcard_name)
    TextView mTvIdcardName;
    @BindView(R.id.tv_idcard_sex)
    TextView mTvIdcardSex;
    @BindView(R.id.tv_idcard_mz)
    TextView mTvIdcardMz;
    @BindView(R.id.tv_idcard_birthday)
    TextView mTvIdcardBirthday;
    @BindView(R.id.tv_idcard_address)
    TextView mTvIdcardAddress;
    @BindView(R.id.tv_idcard_card)
    TextView mTvIdcardCard;
    @BindView(R.id.tv_idcard_info)
    LinearLayout mTvIdcardInfo;
    @BindView(R.id.btn_idcard_commit)
    AppCompatButton mBtnIdcardCommit;
    @BindView(R.id.btn_front_re)
    AppCompatButton mBtnFrontRe;

    private IDCardFrontBean mIDCard;
    private String mPhoto;
    private int mFront = 103;
    RxPermissions mRxPermissions;
    /**
     * 是否拍过照片
     */
    private boolean mIsCheck;

    @Override
    protected void initView() {
        super.initView();
        mToolbarName.setText("身份证正面照");
        mToolbarBack.setOnClickListener(v -> finish());
        mRxPermissions = new RxPermissions(this);
    }

    @Override
    protected void initListener() {
        super.initListener();

        /**
         * 6.0摄像头权限校验
         */
        mIvIdcard.setOnClickListener(v -> {
            mRxPermissions
                    .request(Manifest.permission.CAMERA)
                    .subscribe(aBoolean -> {
                        if (aBoolean) {
                            goCamera();
                        } else {
                            /**
                             * 拒绝
                             */
                            AppCenter.mSpUtil.putBoolean(UserConstant.CAMERA_PERMISSION, aBoolean);
                            showMessage("您拒绝了相机权限,请到设置里开启相机权限");
                        }
                    });
        });
        mBtnFrontRe.setOnClickListener(v -> {
            mRxPermissions
                    .request(Manifest.permission.CAMERA)
                    .subscribe(aBoolean -> {
                        if (aBoolean) {
                            goCamera();
                        } else {
                            /**
                             * 拒绝
                             */
                            showMessage("您拒绝了相机权限,请到设置里开启相机权限");
                        }
                    });
        });
        /**
         * 提交信息
         */
        mBtnIdcardCommit.setOnClickListener(v -> {
            if(mIsCheck){
                String id_card_number = mIDCard.getId_card_number();
                if(id_card_number.contains("*")){
                    showMessage("身份证信息有误,请重新识别身份证");
                    return ;
                }
                mPresenter.sendService(getUserId(),getToken(),mIDCard, mPhoto,mFront);
            }else{
                showMessage("请先扫描身份证");
            }
        });
    }

    public void goCamera() {
        showDialog("联网授权中...");
        String uuid = System.currentTimeMillis()+"";

        Flowable.create((FlowableOnSubscribe<Integer>) e -> {
            Manager manager = new Manager(this);
            IDCardQualityLicenseManager idCardLicenseManager = new IDCardQualityLicenseManager(this);
            manager.registerLicenseManager(idCardLicenseManager);
            manager.takeLicenseFromNetwork(uuid);
            if (idCardLicenseManager.checkCachedLicense() > 0)
                e.onNext(1);
            else
                e.onNext(2);
        }, BackpressureStrategy.BUFFER)
        .compose(T.D())
        .subscribeWith(new Result<Integer>() {
            @Override
            protected void onSuccess(Integer result) {
                dissDialog();
                if(result == 1){
                    Intent intent = new Intent(IdCardFrontActivity.this,
                            com.megvii.idcardlib.IDCardScanActivity.class);
                    intent.putExtra("side", 0);
                    intent.putExtra("isvertical", false);
                    startActivityForResult(intent, mFront);
                }else if(result == 2){
                    showMessage("联网授权失败!");
                }
            }
        });
    }

    @Override
    public void sendFailed(int type) {
        switch (type) {
            case UserConstant.IDCARD_NULL:
                showMessage(R.string.idcardnull);
                break;
            case UserConstant.IDCARD_ERROR:
                showMessage(R.string.idcard_error);
                break;
            case UserConstant.IDCARD_CAMERA_NULL:
                showMessage(R.string.camera_null);
                break;
            case UserConstant.IDCARD_CANCEL:
                showMessage(R.string.cancel);
                break;
            case UserConstant.IDCARD_UNKNOW:
                showMessage(R.string.icard_unknow);
                break;
            case UserConstant.TOKEN_OUT:
                U.tokenOut(this);
                break;
            case 0:
                setError("请重新拍摄!");
                break;
        }
    }

    @Override
    public void sendSuccess(HttpWrapper<String> bean) {
        if (Constant.SUCCESS_CODE.equals(bean.code)) {
            startActivity(new Intent(this, IdCardBackActivity.class));
            finish();
        } else if(Constant.ERROR_CODE.equals(bean.code)){
            showMessage(bean.info);
        }else if(Constant.TOKEN_TIMEOUT.equals(bean.code)){
            U.tokenOut(this);
        }
    }

    @Override
    public void setInfo(byte[] data, IDCardFrontBean idCard) {
        mIsCheck = true;
        mTvIdcard.setVisibility(View.GONE);
        mTvIdcardInfo.setVisibility(View.VISIBLE);
        mIDCard = idCard;
        mPhoto = new String(Base64En.base64Encode(data));
        Glide.with(this)
                .load(data).transform(new GlideOval(this))
                .into(mIvIdcard);

        String strDate = idCard.getBirthday().toString();

        String name = "姓名 : " + idCard.getName();
        String sex = "性别 : " + idCard.getGender();
        String nation = "民族 : " + idCard.getRace();
        String date = "出生日期 : " + strDate;
        String address = "地址 : " + idCard.getAddress();
        String id = "身份证号码 : " + idCard.getId_card_number();

        mTvIdcardName.setText(name);
        mTvIdcardSex.setText(sex);
        mTvIdcardMz.setText(nation);
        mTvIdcardBirthday.setText(date);
        mTvIdcardAddress.setText(address);
        mTvIdcardAddress.setVisibility(View.GONE);
        mTvIdcardCard.setText(id);

        mBtnFrontRe.setText("重拍");
    }

    @Override
    public void setError(String info) {
        U.getSingleDialog(this,"温馨提示",info,"确定",null).show();
        mIvIdcard.setVisibility(View.VISIBLE);
    }

    @Override
    public void reTakePhoto() {
        U.getSlectDialog(this, "温馨提示", "扫描照片质量过低,请重新拍摄", "取消", "重拍", new Listener.OnNormalAlertDialogChooseClickListener() {
            @Override
            public void onLeft() {

            }

            @Override
            public void onRight() {
                goCamera();
            }
        }).show();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_idcardfront;
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mPresenter.sendPic(resultCode, data,mFront,getUserId(),getToken());
    }

    @Override
    public void uploadContactSuccess(HttpWrapper<String> s) {

    }

    @Override
    public void uploadContactFaild() {

    }
    @Override
    protected boolean needFullScreen() {
        return true;
    }
}
